package com.jinzhi.jzweb.controller.backstage;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.constants.MessagesEnum;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.ShiroUtils;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.common.vo.PageInfoVo;
import com.jinzhi.jzweb.domain.JazMessageDO;
import com.jinzhi.jzweb.domain.JazSysProjectDO;
import com.jinzhi.jzweb.domain.JazUserDemandDO;
import com.jinzhi.jzweb.domain.param.UserDemanDQuery;
import com.jinzhi.jzweb.service.JazMessageService;
import com.jinzhi.jzweb.service.JazSysProjectService;
import com.jinzhi.jzweb.service.JazUserDemandService;
import io.swagger.annotations.*;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Optional;

/*
 *  @author : JingChangTian
 *  @date   : 2023/7/11 13:55
 *  @description : 用户需求
 *
 */
@Controller
@RequestMapping("/userDemand")
@Api(value = "用户需求后台管理", tags = "用户需求后台管理")
public class UserDemandController {


    private final JazUserDemandService jazUserDemandService;

    private final JazMessageService jazMessageService;

    private final JazSysProjectService jazSysProjectService;

    public UserDemandController(JazUserDemandService jazUserDemandService, JazMessageService jazMessageService, JazSysProjectService jazSysProjectService) {
        this.jazUserDemandService = jazUserDemandService;
        this.jazMessageService = jazMessageService;
        this.jazSysProjectService = jazSysProjectService;
    }

    @ApiOperation(value = "后台分页查询用户需求列表信息", notes = "后台分页查询用户需求列表信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "UserDemanDQuery", value = "UserDemanDQuery", required = true, dataType = "UserDemanDQuery"),
    })
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功"),
            @ApiResponse(code = 500, message = "服务器内部异常")})
    @ResponseBody
    @PostMapping(value = "/getUserDemandPage")
    public Result<Page<JazUserDemandDO>> getUserDemandPage(@RequestBody UserDemanDQuery userDemanDQuery){
        return Result.ok(jazUserDemandService.getUserDemandPage(userDemanDQuery));
    }

    @Log(value = "审核用户需求信息",sysModule = 3,operationType = 3)
    @ApiOperation(value = "审核用户需求信息", notes = "审核用户需求信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "JazUserAuntDO", value = "JazUserAuntDO", required = true, dataType = "JazUserAuntDO"),
    })
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功"),
            @ApiResponse(code = 500, message = "服务器内部异常")})
    @ResponseBody
    @PostMapping(value = "/examineDeman")
    public Result<String> examineDeman(@RequestBody JazUserDemandDO jazUserDemandDO){
        JazUserDemandDO demandDO = jazUserDemandService.selectById(jazUserDemandDO.getId());
        if (demandDO==null){
            return Result.fail();
        }
        demandDO.setUpdateTime(new Date());
        demandDO.setAuditStatus(1);
        demandDO.setAuditResult(jazUserDemandDO.getAuditResult());
        if (demandDO.getAuditResult()==1){
            if (StringUtil.notEmpty(jazUserDemandDO.getRefuseReason())){
                demandDO.setRefuseReason(jazUserDemandDO.getRefuseReason());
            }else {
                return Result.fail("请输入拒绝原因");
            }
        }
        Boolean  aBoolean = jazUserDemandService.updateById(demandDO);
        // 发送审核消息
        if (demandDO.getAuditResult()==0){
            // 通过
            JazMessageDO jazMessageDO1 = new JazMessageDO();
            jazMessageDO1.setMessageType(1);
            jazMessageDO1.setSenderId(ShiroUtils.getUserId());
            jazMessageDO1.setReceiverId(demandDO.getSysUserid());
            jazMessageDO1.setMessageContent(MessagesEnum.MESSAGE_107.getMsg());
            jazMessageDO1.setMessageNum(MessagesEnum.MESSAGE_107.getNum());
            jazMessageDO1.setDemandId(demandDO.getId());
            jazMessageDO1.setIsRead(0);
            jazMessageService.senMessage(jazMessageDO1);
        } else if (demandDO.getAuditResult()==1) {
            // 拒绝
            JazMessageDO jazMessageDO1 = new JazMessageDO();
            jazMessageDO1.setMessageType(1);
            jazMessageDO1.setSenderId(ShiroUtils.getUserId());
            jazMessageDO1.setReceiverId(demandDO.getSysUserid());
            jazMessageDO1.setMessageContent(MessagesEnum.MESSAGE_108.getMsg()+demandDO.getRefuseReason());
            jazMessageDO1.setMessageNum(MessagesEnum.MESSAGE_108.getNum());
            jazMessageDO1.setDemandId(demandDO.getId());
            jazMessageDO1.setIsRead(0);
            jazMessageService.senMessage(jazMessageDO1);
        }
        return aBoolean ? Result.ok() : Result.fail();
    }


    @ApiOperation(value = "根据用户需求id查询详细信息", notes = "根据用户需求id查询详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Long"),
    })
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功"),
            @ApiResponse(code = 500, message = "服务器内部异常")})
    @ResponseBody
    @GetMapping(value = "/getUserDemandById")
    public Result<JazUserDemandDO> getUserDemandById(@RequestParam("id") Long id){
        return Result.ok(jazUserDemandService.getUserDemandById(id));
    }

    @Log(value = "删除用户需求",sysModule = 3,operationType = 2)
    @ApiOperation(value = "删除用户需求", notes = "删除用户需求")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Long"),
    })
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功"),
            @ApiResponse(code = 500, message = "服务器内部异常")})
    @ResponseBody
    @GetMapping(value = "/deletedById")
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> deletedById(@RequestParam("id") Long id){
        JazUserDemandDO demandDO = jazUserDemandService.selectById(id);
        if (demandDO==null){
            return Result.fail();
        }
        // 删除已经审核过的消息
        jazMessageService.delete(new EntityWrapper<JazMessageDO>()
                .eq("receiver_id",demandDO.getSysUserid())
                .eq("demand_id",demandDO.getId()));
        boolean b = jazUserDemandService.deleteById(id);
        return b?Result.ok():Result.fail();
    }


    @ApiOperation(value = "用户需求详情页面入口", notes = "用户需求详情页面入口")
    @ApiImplicitParams({
    })
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功"),
            @ApiResponse(code = 500, message = "服务器内部异常")})
    @GetMapping("/info/{id}")
    public String info(@PathVariable("id") Long id, Model model){
        model.addAttribute("myData", jazUserDemandService.getUserDemandById(id));
        model.addAttribute("userId",id);
        return "jzweb/jazUserDemand/info";
    }



    /**
     * 分页查询
     * @param pageInfoVo
     * @param jazUserDemandBackgroundDTO
     * @return
     */
    @ResponseBody
    @GetMapping("/backgroundList")
    public Result<Page<JazUserDemandDO>> list(PageInfoVo pageInfoVo, JazUserDemandDO jazUserDemandBackgroundDTO){
        // 查询列表数据
        Page<JazUserDemandDO> page = new Page<>(pageInfoVo.getCurrent(),pageInfoVo.getSize());
        // 条件
        Wrapper<JazUserDemandDO> wrapper = new EntityWrapper<JazUserDemandDO>()
                .like(StringUtil.notEmpty(jazUserDemandBackgroundDTO.getTitle()),"title",jazUserDemandBackgroundDTO.getTitle())
                .like(StringUtil.notEmpty(jazUserDemandBackgroundDTO.getUserName()),"user_name",jazUserDemandBackgroundDTO.getUserName())
                .eq(jazUserDemandBackgroundDTO.getProjectId()!=null,"project_id",jazUserDemandBackgroundDTO.getProjectId())
                .eq(jazUserDemandBackgroundDTO.getStatus()!=null,"status",jazUserDemandBackgroundDTO.getStatus())
                .eq("demand_source",2)
                .orderBy("create_time",false);
        // 查询
        Page<JazUserDemandDO> doPage = jazUserDemandService.selectPage(page, wrapper);
        //查询项目类型
        doPage.getRecords().forEach(jazUserDemandBackgroundDO -> {
            if(jazUserDemandBackgroundDO.getProjectId()!=null) {
                JazSysProjectDO jazSysProjectDO = Optional.ofNullable(jazSysProjectService
                        .selectById(jazUserDemandBackgroundDO.getProjectId())).orElse(new JazSysProjectDO());
                jazUserDemandBackgroundDO.setProjectName(jazSysProjectDO.getName());
            }
        });
        return Result.ok(doPage);
    }


    /**
     * 后台根据id查询详情
     * @param id
     * @return
     */
    @ResponseBody
    @GetMapping("/backgroundGetById")
    public Result<JazUserDemandDO> edit(@RequestParam("id") Long id){
        return jazUserDemandService.selectDemandById(id);
    }


    @Log(value = "添加后台需求表",sysModule = 3,operationType = 1)
    @ResponseBody
    @PostMapping("/backgroundSave")
    //@RequiresPermissions("jzweb:jazUserDemandBackground:add")
    public Result<String> save(@RequestBody JazUserDemandDO jazUserDemandDO){
        return jazUserDemandService.insertDemand(jazUserDemandDO);
    }

    @Log(value = "修改后台需求表",sysModule = 3,operationType = 3)
    @ResponseBody
    @PostMapping("/backgroundUpdate")
    //@RequiresPermissions("jzweb:jazUserDemandBackground:edit")
    public Result<String>  update(@RequestBody JazUserDemandDO jazUserDemandDO){
        return jazUserDemandService.updateDemand(jazUserDemandDO);
    }

    @Log(value = "删除后台需求表",sysModule = 3,operationType = 2)
    @PostMapping( "/backgroundRemove")
    @ResponseBody
    //@RequiresPermissions("jzweb:jazUserDemandBackground:remove")
    public Result<String>  remove(@RequestParam("id") Long id){
        boolean b = jazUserDemandService.deleteById(id);
        return b?Result.ok():Result.fail();
    }



}
